import router from '@system.router'
import prompt from '@system.prompt'
import storage from '@system.storage'
import voice from '@system.voice'
import ai from '@system.ai'

export default {
  data: {
    caseId: 0,
    currentCase: null,
    currentSuspect: null,
    suspects: [],
    conversationHistory: [],
    currentQuestion: '',
    isRecording: false,
    suspectEmotion: 'neutral',
    suspicionLevel: 0,
    evidenceFound: [],
    interrogationSkills: {
      psychology: 1,
      observation: 1,
      logic: 1
    },
    aiPersonality: {
      tone: 'professional',
      approach: 'direct'
    }
  },

  onInit() {
    const params = router.getParams()
    this.caseId = params.caseId
    this.loadCaseData()
    this.loadInterrogationSkills()
  },

  onShow() {
    this.saveCurrentProgress()
  },

  loadCaseData() {
    storage.get({
      key: 'cases',
      success: (data) => {
        if (data) {
          const cases = JSON.parse(data.data || data)
          this.currentCase = cases.find(c => c.id === this.caseId)
          if (this.currentCase) {
            this.suspects = this.generateSuspectProfiles()
            this.currentSuspect = this.suspects[0]
          }
        }
      }
    })
  },

  generateSuspectProfiles() {
    // 生成嫌疑人档案和AI性格
    return this.currentCase.suspects.map((name, index) => ({
      id: index,
      name: name,
      age: 25 + Math.floor(Math.random() * 40),
      occupation: this.getRandomOccupation(),
      personality: this.getRandomPersonality(),
      relationship: this.getRandomRelationship(),
      alibi: this.generateAlibi(),
      secrets: this.generateSecrets(),
      lyingProbability: Math.random() * 0.8,
      cooperationLevel: Math.random(),
      emotionalState: 'calm',
      stressLevel: 0,
      contradictions: []
    }))
  },

  getRandomOccupation() {
    const occupations = ['商人', '教师', '医生', '律师', '艺术家', '工程师', '服务员', '司机']
    return occupations[Math.floor(Math.random() * occupations.length)]
  },

  getRandomPersonality() {
    const personalities = ['冷静', '紧张', '自信', '内向', '外向', '狡猾', '诚实', '多疑']
    return personalities[Math.floor(Math.random() * personalities.length)]
  },

  getRandomRelationship() {
    const relationships = ['朋友', '同事', '亲戚', '邻居', '陌生人', '商业伙伴', '竞争对手']
    return relationships[Math.floor(Math.random() * relationships.length)]
  },

  generateAlibi() {
    const alibis = [
      '在家看电视',
      '和朋友聚餐',
      '在公司加班',
      '在健身房锻炼',
      '在超市购物',
      '在医院看病',
      '在机场接人',
      '在图书馆学习'
    ]
    return alibis[Math.floor(Math.random() * alibis.length)]
  },

  generateSecrets() {
    const secrets = [
      '有犯罪前科',
      '欠下巨额债务',
      '与受害者有私仇',
      '掌握重要证据',
      '知道受害者的秘密',
      '曾经威胁过受害者',
      '有不在场证明',
      '是受害者的秘密情人'
    ]
    return secrets.slice(0, 2 + Math.floor(Math.random() * 3))
  },

  loadInterrogationSkills() {
    storage.get({
      key: 'playerData',
      success: (data) => {
        if (data) {
          const playerData = JSON.parse(data.data || data)
          this.interrogationSkills = playerData.interrogationSkills
        }
      }
    })
  },

  startVoiceRecording() {
    if (this.isRecording) return
    
    this.isRecording = true
    voice.startListening({
      success: (result) => {
        this.currentQuestion = result.text
        this.sendQuestion()
        this.isRecording = false
      },
      fail: (error) => {
        prompt.showToast({
          message: '语音识别失败: ' + error.message,
          duration: 2000
        })
        this.isRecording = false
      }
    })
  },

  sendQuestion() {
    if (!this.currentQuestion.trim()) return

    const question = this.currentQuestion.trim()
    this.addMessage('detective', question)
    
    // 分析问题的类型和效果
    const questionAnalysis = this.analyzeQuestion(question)
    
    // 生成AI回复
    this.generateAIResponse(question, questionAnalysis)
    
    this.currentQuestion = ''
  },

  analyzeQuestion(question) {
    const lowerQuestion = question.toLowerCase()
    let type = 'general'
    let effectiveness = 0.5
    
    // 分析问题类型
    if (lowerQuestion.includes('不在场') || lowerQuestion.includes('当时')) {
      type = 'alibi'
      effectiveness = 0.7
    } else if (lowerQuestion.includes('关系') || lowerQuestion.includes('认识')) {
      type = 'relationship'
      effectiveness = 0.6
    } else if (lowerQuestion.includes('秘密') || lowerQuestion.includes('隐瞒')) {
      type = 'secret'
      effectiveness = 0.8
    } else if (lowerQuestion.includes('说谎') || lowerQuestion.includes('撒谎')) {
      type = 'confrontation'
      effectiveness = 0.9
    } else if (lowerQuestion.includes('证据') || lowerQuestion.includes('证明')) {
      type = 'evidence'
      effectiveness = 0.75
    }
    
    // 根据审讯技能调整效果
    effectiveness *= (1 + this.interrogationSkills.psychology * 0.1)
    effectiveness *= (1 + this.interrogationSkills.logic * 0.1)
    
    return { type, effectiveness }
  },

  generateAIResponse(question, analysis) {
    // 生成AI嫌疑人的回复
    const suspect = this.currentSuspect
    const isLying = Math.random() < suspect.lyingProbability * (1 - analysis.effectiveness)
    
    let response = ''
    let emotionChange = 0
    let stressChange = 0
    
    switch (analysis.type) {
      case 'alibi':
        if (isLying) {
          response = this.generateLyingAlibi(suspect)
          stressChange += 0.2
        } else {
          response = `我当时正在${suspect.alibi}，这是千真万确的。`
        }
        break
        
      case 'relationship':
        if (isLying) {
          response = this.generateLyingRelationship(suspect)
          emotionChange -= 0.1
        } else {
          response = `我和受害者只是${suspect.relationship}关系，没有深交。`
        }
        break
        
      case 'secret':
        if (isLying) {
          response = this.generateLyingSecret(suspect)
          stressChange += 0.3
        } else if (Math.random() < 0.3) {
          const secret = suspect.secrets[Math.floor(Math.random() * suspect.secrets.length)]
          response = `好吧，我承认我${secret}，但这与案件无关。`
          this.evidenceFound.push(secret)
        } else {
          response = `我没有什么可隐瞒的，我所有的秘密都与案件无关。`
        }
        break
        
      case 'confrontation':
        if (isLying) {
          response = this.generateDefensiveResponse(suspect)
          emotionChange -= 0.3
          stressChange += 0.4
        } else {
          response = `我没有说谎！我说的都是实话，你可以去调查！`
        }
        break
        
      case 'evidence':
        response = this.generateEvidenceResponse(suspect, isLying)
        break
        
      default:
        response = this.generateGeneralResponse(suspect, isLying)
        break
    }
    
    // 更新嫌疑人状态
    suspect.stressLevel = Math.max(0, Math.min(1, suspect.stressLevel + stressChange))
    suspect.emotionalState = this.updateEmotionalState(suspect.emotionalState, emotionChange)
    
    // 添加矛盾检测
    if (isLying && analysis.effectiveness > 0.7) {
      this.detectContradiction(suspect, analysis.type)
    }
    
    // 添加回复到对话历史
    this.addMessage('suspect', response, {
      lying: isLying,
      emotion: suspect.emotionalState,
      stress: suspect.stressLevel
    })
    
    // 更新审讯进度
    this.updateInterrogationProgress(analysis, isLying)
  },

  generateLyingAlibi(suspect) {
    const lyingAlibis = [
      `我当时在家，但是...没有人可以证明。`,
      `我在外面散步，具体时间记不清了。`,
      `我在朋友家，但是朋友现在不在城里。`,
      `我在工作，但是监控那天正好坏了。`
    ]
    return lyingAlibis[Math.floor(Math.random() * lyingAlibis.length)]
  },

  generateLyingRelationship(suspect) {
    const lyingRelationships = [
      `我们只是普通朋友，很少联系。`,
      `我不怎么了解他，只是听说过。`,
      `我们关系一般，没有什么特别的。`,
      `只是点头之交，没有深入交往。`
    ]
    return lyingRelationships[Math.floor(Math.random() * lyingRelationships.length)]
  },

  generateLyingSecret(suspect) {
    const lyingSecrets = [
      `我没有什么秘密，我很坦白的。`,
      `我的过去很清白，没有什么可隐瞒的。`,
      `我所有的秘密都与案件无关。`,
      `我不想谈论我的私事，但这不重要。`
    ]
    return lyingSecrets[Math.floor(Math.random() * lyingSecrets.length)]
  },

  generateDefensiveResponse(suspect) {
    const defensiveResponses = [
      `你这是在冤枉我！我有权保持沉默！`,
      `我不需要回答这个问题！找我的律师来！`,
      `你凭什么说我说谎？有证据吗？`,
      `我拒绝回答！这是对我的侮辱！`
    ]
    return defensiveResponses[Math.floor(Math.random() * defensiveResponses.length)]
  },

  generateEvidenceResponse(suspect, isLying) {
    if (isLying) {
      return `我不知道你在说什么！那些证据可能是伪造的！`
    } else {
      return `如果有证据你就拿出来！我是清白的！`
    }
  },

  generateGeneralResponse(suspect, isLying) {
    if (isLying) {
      const lyingGeneral = [
        `这个...我不太记得了。`,
        `可能吧，我也说不清楚。`,
        `时间太久了，我记不清细节了。`,
        `我不太想谈论这个话题。`
      ]
      return lyingGeneral[Math.floor(Math.random() * lyingGeneral.length)]
    } else {
      const truthfulGeneral = [
        `我会配合调查的，问吧。`,
        `我想帮助破案，尽管问。`,
        `我没有什么可隐瞒的。`,
        `我会如实回答你的问题。`
      ]
      return truthfulGeneral[Math.floor(Math.random() * truthfulGeneral.length)]
    }
  },

  updateEmotionalState(currentState, change) {
    const states = ['calm', 'nervous', 'angry', 'defensive', 'cooperative']
    const currentIndex = states.indexOf(currentState)
    const newIndex = Math.max(0, Math.min(states.length - 1, currentIndex + Math.round(change * 2)))
    return states[newIndex]
  },

  detectContradiction(suspect, questionType) {
    const contradiction = {
      type: questionType,
      timestamp: new Date().toISOString(),
      description: `嫌疑人在${questionType}问题上可能说谎`
    }
    suspect.contradictions.push(contradiction)
    
    prompt.showToast({
      message: '发现矛盾点！',
      duration: 2000
    })
  },

  updateInterrogationProgress(analysis, isLying) {
    // 更新审讯进度和玩家经验
    if (isLying && analysis.effectiveness > 0.7) {
      this.suspicionLevel += 0.1
      this.addExperience(10)
    } else if (!isLying && analysis.effectiveness > 0.8) {
      this.suspicionLevel -= 0.05
      this.addExperience(5)
    }
  },

  addExperience(exp) {
    storage.get({
      key: 'playerData',
      success: (data) => {
        if (data) {
          const playerData = JSON.parse(data.data || data)
          playerData.experience += exp
          
          // 检查升级
          if (playerData.experience >= playerData.level * 100) {
            playerData.level++
            playerData.experience = 0
            
            prompt.showToast({
              message: `恭喜升级到${playerData.level}级！`,
              duration: 3000
            })
          }
          
          storage.set({
            key: 'playerData',
            value: JSON.stringify(playerData)
          })
        }
      }
    })
  },

  addMessage(sender, content, metadata = {}) {
    const message = {
      id: Date.now(),
      sender: sender,
      content: content,
      timestamp: new Date().toLocaleTimeString('zh-CN'),
      metadata: metadata
    }
    
    this.conversationHistory.push(message)
    
    // 限制历史记录长度
    if (this.conversationHistory.length > 100) {
      this.conversationHistory = this.conversationHistory.slice(-100)
    }
  },

  switchSuspect(suspectId) {
    this.currentSuspect = this.suspects.find(s => s.id === suspectId)
    this.addMessage('system', `现在开始审讯${this.currentSuspect.name}`)
  },

  analyzeEvidence() {
    router.push({
      uri: 'pages/evidence/evidence',
      params: {
        caseId: this.caseId,
        evidence: this.evidenceFound,
        contradictions: this.currentSuspect.contradictions
      }
    })
  },

  makeConclusion() {
    const conclusion = {
      suspectId: this.currentSuspect.id,
      suspicionLevel: this.suspicionLevel,
      evidenceCount: this.evidenceFound.length,
      contradictionCount: this.currentSuspect.contradictions.length,
      stressLevel: this.currentSuspect.stressLevel
    }
    
    router.push({
      uri: 'pages/conclusion/conclusion',
      params: conclusion
    })
  },

  saveCurrentProgress() {
    const progress = {
      caseId: this.caseId,
      currentSuspect: this.currentSuspect,
      conversationHistory: this.conversationHistory,
      evidenceFound: this.evidenceFound,
      suspicionLevel: this.suspicionLevel
    }
    
    storage.set({
      key: 'currentCase',
      value: JSON.stringify(progress)
    })
  }
}